// app/controller/upload.js
const Controller = require('egg').Controller;
const path = require('path');
const fs = require('fs');

class UploadController extends Controller {
  async upload() {
    const { ctx } = this;
    console.log('拿到上传文件：',ctx.request.files[0]);
    const file = ctx.request.files[0]; // 获取上传的文件

    // 使用相对路径指向项目根目录下的 public 目录
    let uploadPath = path.join(this.config.baseDir, 'app/public/uploads');

    if (file) {
      // 读取文件
      let fileData = fs.readFileSync(file.filepath) //files[0]表示获取第一个文件，若前端上传多个文件则可以遍历这个数组对象
      // 创建 uploads 目录如果它不存在
      if (!fs.existsSync(uploadPath)) {
        fs.mkdirSync(uploadPath, { recursive: true });
      }

      await  fs.writeFileSync(path.join('app/public/uploads', `${file.filename}`), fileData)
      // 返回一个相对于 public 目录的 URL
      ctx.body = { url: `/public/uploads/${name}` };
    } else {
      ctx.status = 400;
      ctx.body = { message: 'No file uploaded.' };
    }
  }
}

module.exports = UploadController;
